package com.mindbook.vip.gawxchatinfo.utils.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mindbook.vip.gawxchatinfo.exception.wx.AccessTokenException;
import com.mindbook.vip.gawxchatinfo.exception.wx.PhoneNumberException;
import com.mindbook.vip.gawxchatinfo.utils.http.HttpRequestUtils;
import com.mindbook.vip.gawxchatinfo.utils.result.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @NAME: wxb
 * @DATE: 2022/4/16
 * @Description 通过code 获取手机号
 **/
@Component
public class PhoneNumberUtils {

    private static final String PHONE_NUMBER_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";

    @Autowired
    private AccessTokenUtils accessTokenUtils;

    @Autowired
    private HttpRequestUtils httpRequestUtils;

    /**
     * 通过code 获取phoneNumber
     * accessToken的值已经在文中获取到了
     * @param code
     * @return
     */
    public String getPhoneNumber(String code) {
        //发送post请求的参数
        String accessToken = accessTokenUtils.getAccessToken();

        JSONObject params = new JSONObject();
        params.put("code", code);

        //整理url
        String url = PHONE_NUMBER_URL + "?access_token=" + accessToken;
        //发送请求
        String result = httpRequestUtils.sendPostRequest(url, params);
//        System.out.println("result:" + result);

        //解析返回结果
        JSONObject resultJson = JSON.parseObject(result);
        String errcode = resultJson.getString("errcode");

        if (errcode.equals("0")) {
            //如果返回中的数据的errcode的值为0，则将手机号返回去
            String phoneInfo = resultJson.getString("phone_info");
            JSONObject phoneInfoJson = JSONObject.parseObject(phoneInfo);
            return phoneInfoJson.getString("phoneNumber");
        } else {
            //如果获取数据不存在，则获取当前的错误提示
            String errMsg = getErrMsg(errcode);
            throw new PhoneNumberException(Integer.parseInt(errcode), errMsg);
        }
    }

    private String getErrMsg(String code) {
        String errMsg = "";
        switch (code) {
            case "-1":
                errMsg = ResultEnum.PHONE_NUMBER_SYSTEM_BUSY.getMsg();
                break;
            case "40029":
                errMsg = ResultEnum.PHONE_NUMBER_CODE_ERROR.getMsg();
                break;
            default:
                errMsg = "获取phoneNumber的错误不在列表内";
        }
        return errMsg;
    }


}
